package cn.ex.org.controller;

import cn.ex.basic.util.AjaxResult;
import cn.ex.basic.util.PageList;
import cn.ex.org.domain.Department;
import cn.ex.org.query.DepartmentQuery;
import cn.ex.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: ZeWangmu
 * @Date: 2022/06/06/20:19
 * @Description: 部门管理请求和响应的接口
 */
@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public List<Department> findAll(){
        return departmentService.findAll();
    }
    /**
     * 查询一条
     */
    @GetMapping("/{id}")
    public Department findById(@PathVariable("id") Long id){
        return  departmentService.findById(id);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            departmentService.removeById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统瓦了");

        }
    }

    /**
     * 高级+分页查询
     * @param departmentQuery
     * @return
     */
   @PostMapping
    public PageList<Department> query(@RequestBody DepartmentQuery departmentQuery){
       return departmentService.queryPage(departmentQuery);
    }

    /**
     * 新增或修改
     * @param department
     * @return
     */
    @PutMapping
    public AjaxResult addOrUpt(@RequestBody Department department) {
        try {
            if (department.getId() == null) {
                departmentService.save(department);
            } else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统瓦了");
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody Long[] ids){
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统瓦了");

        }
    }
    /**
     * 分层查询
     * @return
     */
    @GetMapping("/tree")
    public List<Department> searchTree(){
        return departmentService.searchTree();
    }


}
